﻿#include "GLLInc.h"
#include "GLLOSApp.h"
#include "GLLGameApp.h"

#pragma comment( lib, "GLL.lib" )
 
namespace GLL
{
	void OSApp::MoveOSWindow( const Size2Di& client_size)
	{
		Size2Di wnd_size = GetFrameSizeFromClientSize_spec(client_size);
		Size2Di ss = GetScreenSize_spec();
		int left = (ss.width - wnd_size.width) / 2;
		int top = (ss.height - wnd_size.height) / 2;
		MoveOSWindow_spec( Area2Di(left, top, wnd_size.width, wnd_size.height));
	}

	void OSApp::UpdateWindowTitle()
	{
		StringStream title;
		GetOSAppTitle(title);
		SetOSAppTitle_spec(title);
	}

	void OSApp::Loop()
	{
		while( !_game->IsGameExiting() )
		{
			ProcOSMessage_spec();
			UpdateWindowTitle();
			_game->Update();
		}
	}

	void OSApp::Start(GameApp* pGameApp, GameState& startState)
	{
#ifdef GLL_DEBUG
		_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
		//_CrtSetBreakAlloc();
#endif

		_game = pGameApp;
		if(!_game) GLL_Throw("Must have GameApp to create OS Application");

		CreateOSWindow_spec();
		ShowOSWindow_spec();
		_game->_Start(startState);

		Loop();
	}

	void OSApp::Shutdown()
	{
		_game->Shutdown(); 
	}

	OSApp::OSApp( )
	{
		_game = 0;
		Reset();
	}

	Size2Di OSApp::GetWindowInitialSize()
	{
		return Size2Di (800, 600);
	}

	void OSApp::GetOSAppTitle( StringStream& out )
	{
		out << "title";
	}


	Size2Di OSApp::GetClientSizeFromFrameSize( const Size2Di& size )
	{
		//算出边框的大小
		Size2Di client;
		client.width = 1000;
		client.height = 1000;
		Size2Di frame = GetFrameSizeFromClientSize_spec(client);
		Size2Di offset;
		offset.width = frame.width - client.width;
		offset.height = frame.height - client.height;

		//从外框减去
		Size2Di ret;
		ret.width = size.width - offset.width;
		ret.height = size.height - offset.height;
		return ret;
	}


	void OSApp::SetClientSize( const Size2Di& s )
	{
		DoSetClientSize_spec(s);
		OnClientSizeChanged_spec(s);
	}

	void OSApp::Reset()
	{
		_hWnd = 0;
		_TRACE = 0;
		_Console = 0;
		_startBkgnd = 0;
	}

	void OSApp::Start_CatchSoftException(GameApp* pGameApp, GameState& startState)
	{
		GLL_Try;
		Start(pGameApp, startState);
		GLL_Catch;
	}

	void OSApp::Start_CatchAllException(GameApp* pGameApp, GameState& startState)
	{
		GLL_OSTry;
		Debug::OSException::InitLOG(Debug::OSException::LCT_Both);
		Debug::OSException::SkipInDebugger(false);
		Start_CatchSoftException(pGameApp, startState);
		GLL_OSCatch;
		GLL_END;
	}

};//GLL

